<template>
  <view class="container">
    <view class="navbar">
      <view class="navbar-title">修改复查项目</view>
    </view>
    
    <scroll-view class="content" scroll-y>
      <view class="form-item">
        <view class="form-label required">复查项目</view>
        <FormPicker 
          v-model="form.projectName" 
          :options="projectOptions" 
          placeholder="请选择复查项目"
          :required="true"
          @change="handleProjectChange"
          :disabled="isExpired"  <!-- 已过期时禁用 -->
        ></FormPicker>
      </view>
      
      <!-- 其他项目输入框 -->
      <view class="form-item" v-if="form.projectName === '其它'">
        <view class="form-label required">复查项目名称</view>
        <FormInput 
          v-model="form.otherProjectName" 
          placeholder="请输入复查项目"
          :required="true"
          :disabled="isExpired"  <!-- 已过期时禁用 -->
        ></FormInput>
      </view>
      
      <view class="form-item">
        <view class="form-label required">复查时间</view>
        <DatePickerField 
          v-model="form.reviewTime" 
          placeholder="请选择复查时间"
          :required="true"
          :disabled="isExpired"  <!-- 已过期时禁用 -->
          format="YYYY-MM-DD"  <!-- 只显示到天 -->
        ></DatePickerField>
      </view>
      
      <view class="form-item">
        <view class="form-label required">预约时间</view>
        <DatePickerField 
          v-model="form.appointmentTime" 
          placeholder="请选择预约时间"
          :required="true"
          :disabled="isExpired"  <!-- 已过期时禁用 -->
          format="YYYY-MM-DD"  <!-- 只显示到天 -->
        ></DatePickerField>
      </view>
      
      <view class="form-item">
        <view class="form-label required">是否空腹</view>
        <FormPicker 
          v-model="form.isEmpty" 
          :options="emptyOptions" 
          placeholder="请选择是否空腹"
          :required="true"
          :disabled="isExpired"  <!-- 已过期时禁用 -->
        ></FormPicker>
      </view>
      
      <view class="form-item">
        <view class="form-label">复查结果</view>
        <!-- 图片上传组件 - 负责显示和上传图片 -->
        <ImageUploader
          v-model:modelValue="form.images"
          label=""  <!-- 清空标签，因为我们已经在form-label中定义了 -->
          :disabled="false"  <!-- 始终允许修改图片 -->
        ></ImageUploader>
      </view>
    </scroll-view>
    
    <view class="submit-button" @click="submitForm" :disabled="!canSubmit">
      <text>提交</text>
    </view>
  </view>
</template>

<script>
import FormPicker from '../../components/FormPicker.vue';
import FormInput from '../../components/FormInput.vue';
import DatePickerField from '../../components/DatePickerField.vue';
import ImageUploader from '../../components/ImageUploader.vue';
import config from '../../config.js';

export default {
  components: {
    FormPicker,
    FormInput,
    DatePickerField,
    ImageUploader
  },
  computed: {
    // 控制提交按钮状态：未过期可提交，已过期只有图片修改后可提交
    canSubmit() {
      if (!this.isExpired) {
        return true;
      }
      // 已过期时，只有当图片有变化时才能提交
      return this.form.images !== this.originalImages;
    }
  },
  data() {
    return {
      id: '',
      form: {
        projectName: null,
        otherProjectName: '',
        reviewTime: '',
        appointmentTime: '',
        isEmpty: null,
        images: ''
      },
      originalImages: '', // 保存原始图片地址，用于判断是否修改
      projectOptions: ['甲功', '血钙', '颈部超声', '其它'],
      emptyOptions: ['是', '否'],
      isExpired: false,
      currentReviewItem: null
    };
  },
  onLoad(options) {
    this.id = options.id;
    this.currentReviewItem = uni.getStorageSync('currentReviewItem');
    console.log(this.currentReviewItem)
	
    if (this.currentReviewItem) {
      this.initFormData();
    } else {
      uni.showToast({
        title: '获取项目信息失败',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  methods: {
    // 初始化表单数据
    initFormData() {
      const item = this.currentReviewItem;
      console.log(item.images)
      
      // 处理日期格式，只保留年月日
      const formatDateToDay = (dateStr) => {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
      };
      
      this.form = {
        projectName: this.projectOptions.includes(item.projectName) 
          ? item.projectName 
          : '其它',
        otherProjectName: this.projectOptions.includes(item.projectName) 
          ? '' 
          : item.projectName,
        reviewTime: formatDateToDay(item.reviewTime),
        appointmentTime: formatDateToDay(item.appointmentTime),
        isEmpty: item.isEmpty,
        images: item.images || ''
      };
      
      // 保存原始图片地址
      this.originalImages = item.images || '';
      
      // 判断是否过期（精确到天）
      const now = new Date();
      now.setHours(0, 0, 0, 0);
      const reviewDate = new Date(item.reviewTime);
      reviewDate.setHours(0, 0, 0, 0);
      this.isExpired = reviewDate < now;
    },
    
    // 预览图片功能由ImageUploader组件内部实现
    
    handleProjectChange() {
      if (this.form.projectName !== '其它') {
        this.form.otherProjectName = '';
      }
    },
    
    // 验证表单
    validateForm() {
      const { projectName, otherProjectName, reviewTime, appointmentTime, isEmpty } = this.form;
      const errors = [];
      
      // 已过期时不需要验证其他字段，只验证图片（可选）
      if (!this.isExpired) {
        if (!projectName) {
          errors.push('请选择复查项目');
        } else if (projectName === '其它' && !otherProjectName) {
          errors.push('请输入复查项目名称');
        }
        
        if (!reviewTime) {
          errors.push('请选择复查时间');
        } else {
          const now = new Date();
          now.setHours(0, 0, 0, 0);
          const reviewDate = new Date(reviewTime);
          reviewDate.setHours(0, 0, 0, 0);
          
          if (reviewDate < now) {
            errors.push('复查时间必须晚于或等于当前天数');
          }
        }
        
        if (!appointmentTime) {
          errors.push('请选择预约时间');
        } else {
          const now = new Date();
          now.setHours(0, 0, 0, 0);
          const appointmentDate = new Date(appointmentTime);
          appointmentDate.setHours(0, 0, 0, 0);
          const reviewDate = new Date(reviewTime);
          reviewDate.setHours(0, 0, 0, 0);
          
          if (appointmentDate < now) {
            errors.push('预约时间必须晚于或等于当前天数');
          }
          
          if (appointmentDate > reviewDate) {
            errors.push('预约时间必须早于复查时间');
          }
        }
        
        if (isEmpty === null) {
          errors.push('请选择是否空腹');
        }
      }
      
      if (errors.length > 0) {
        uni.showToast({
          title: errors.join('；'),
          icon: 'none',
          duration: 3000
        });
        return false;
      }
      
      return true;
    },
    
    // 提交表单
    submitForm() {
      if (!this.validateForm()) {
        return;
      }
      
      const projectName = this.form.projectName === '其它' 
        ? this.form.otherProjectName 
        : this.form.projectName;
      
      const formData = {
        id: this.currentReviewItem.id,
        projectName,
        reviewTime: this.form.reviewTime,
        appointmentTime: this.form.appointmentTime,
        isEmpty: this.form.isEmpty,
        images: this.form.images
      };
      
      uni.request({
        url: `${config.baseUrl}/puwai/updateReviewInfo`,
        method: 'POST',
        data: formData,
        header: {
          'Content-Type': 'application/json',
          'Authorization': uni.getStorageSync('token') || ''
        },
        success: (res) => {
          if (res.data && res.data.code === 1) {
            uni.showToast({
              title: '成功更新复查项目',
              icon: 'success'
            });
            
            setTimeout(() => {
              uni.navigateBack();
            }, 2000);
          } else {
            uni.showToast({
              title: res.data.msg || '更新失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('更新复查项目失败:', err);
          uni.showToast({
            title: '更新失败',
            icon: 'none'
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.navbar {
  height: 44px;
  background-color: #1677ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 16px;
}

.navbar-title {
  font-size: 17px;
  font-weight: bold;
}

.content {
  flex: 1;
  padding: 20rpx;
}

.form-item {
  margin-bottom: 20rpx;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: inline-block;
}

.required::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 5rpx;
}

.submit-button {
  height: 100rpx;
  background-color: #1677ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  margin: 20rpx;
  border-radius: 10rpx;
}

.submit-button:disabled {
  background-color: #ccc;
}
</style>
